#include "qthttputils.h"


QtHttpUtils::QtHttpUtils()
{

}

QJsonObject QtHttpUtils::get(const QUrl &url)
{
    QNetworkRequest request;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    // 设置参数
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    // 这里要将json格式的数据转换为QByteArray
    QNetworkReply * reply_ = manager->get(request);
    connect(reply_, &QNetworkReply::errorOccurred,[&](QNetworkReply::NetworkError code)
    {
        switch(static_cast<int>(code))
        {
            case QNetworkReply::ConnectionRefusedError:
                qDebug() << "远程服务器拒绝连接（服务器不接受请求）";
                break;
            case QNetworkReply::HostNotFoundError:
                qDebug() << "找不到远程主机名（无效的主机名）";
                break;
            case QNetworkReply::TimeoutError:
                qDebug() << "与远程服务器的连接超时";
                break;
            default:
                break;
        }
    });
    // 同步等待
    QEventLoop eventLoop;
    connect(reply_, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    QByteArray data = reply_->readAll();
    reply_->deleteLater();
    QJsonDocument respDocument = QJsonDocument::fromJson(data);
    QJsonObject respData = respDocument.object();
    return respData;
}

QJsonObject QtHttpUtils::post(const QUrl &url, const QJsonObject& param)
{
    QNetworkRequest request;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    // 设置参数
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    QJsonDocument document=QJsonDocument(param);
    // 这里要将json格式的数据转换为QByteArray
    QByteArray post_data = document.toJson(QJsonDocument::Compact);
    QNetworkReply * reply_ = manager->post(request, post_data);
    connect(reply_, &QNetworkReply::errorOccurred,[&](QNetworkReply::NetworkError code)
    {
        switch(static_cast<int>(code))
        {
            case QNetworkReply::ConnectionRefusedError:
                qDebug() << "远程服务器拒绝连接（服务器不接受请求）";
                break;
            case QNetworkReply::HostNotFoundError:
                qDebug() << "找不到远程主机名（无效的主机名）";
                break;
            case QNetworkReply::TimeoutError:
                qDebug() << "与远程服务器的连接超时";
                break;
            default:
                break;
        }
    });
    // 同步等待
    QEventLoop eventLoop;
    connect(reply_, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    QByteArray data = reply_->readAll();
    reply_->deleteLater();
    QJsonDocument respDocument = QJsonDocument::fromJson(data);
    QJsonObject respData = respDocument.object();
    return respData;
}


